<?php

namespace app\common\model\fp;

use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use think\model\relation\BelongsTo;

/**
 * Audit
 */
class PostAudit extends Model
{
    // 表名
    protected $name = 'fp_post_audit';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    protected $updateTime = false;

    protected $type = [
        'id' => 'string',
    ];

    protected static function onBeforeInsert($model): void
    {
        $pk = $model->getPk();
        $model->$pk = \app\common\library\SnowFlake::generateParticle();
    }

    public function getIdAttr($value): string
    {
        return (string)$value;
    }

    public function getPostIdAttr($value): string
    {
        return (string)$value;
    }

    /**
     * 如果表不存在，则创建新表
     */
    public static function createTableIfNotExists($tableName = ''): bool
    {
        $cacheKey = 'makeTable:' . $tableName;
        $check = Cache::get($cacheKey);
        if ($check) {
            return true;
        }
        // 检查表是否存在
        $exists = Db::query("SHOW TABLES LIKE  '{$tableName}'");

        if (!$exists) {
            $sql = <<<SQL
            CREATE TABLE `{$tableName}`  (
             `id` bigint(20) unsigned NOT NULL COMMENT 'ID',
              `status` enum('0','1','2') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0' COMMENT '审核状态: 0审核中 1通过 2拒绝',
              `type` enum('0','1') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '0' COMMENT '类型：0正常  1精选',
              `media_type` enum('image','video','unknown') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'unknown' COMMENT '媒体类型',
              `post_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '动态id',
              `user_id` bigint(20) unsigned NOT NULL DEFAULT '0' COMMENT '发动态的用户id',
              `audit_user_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '审核人员',
              `audit_reason` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '审核理由',
              `create_time` int(11) DEFAULT NULL COMMENT '创建时间',
              `snapshot_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '截图任务状态：0 未完成  1已完成',
              `update_time` int(11) DEFAULT NULL COMMENT '审核时间',
              `video_cover_url_bak` varchar(2000) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '封面截图候选',
              `video_cover_url` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '视频选中封面',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC COMMENT='朋友圈-动态审核';
        SQL;

            try {
                Db::execute($sql);
            } catch (\Throwable $e) {
                // 记录异常信息
                Log::channel('my')->error("Failed to create table {$tableName}: " . $e->getMessage());
                // 可以选择抛出异常或返回错误信息
                throw new \RuntimeException("Failed to create table: " . $e->getMessage(), 0, $e);
            }
        }

        Cache::set($cacheKey, 1);

        return true;
    }

    /**
     * 实例化表
     * @return PostAudit
     */
    public static function initModel(): PostAudit
    {
        $model = new self();
        $tableName = 'fp_post_audit_' . date('Y');
        $model->setName($tableName);

        $prefix = config('database.connections.mysql.prefix');
        self::createTableIfNotExists($prefix . $tableName);

        return $model;
    }

    /**
     * 初始化分表表名
     */
    public static function initTable()
    {
        $tableName = 'fp_post_audit_' . date('Y');
        $prefix = config('database.connections.mysql.prefix');
        $tableName = $prefix . $tableName;

        //创建表
        self::createTableIfNotExists($tableName);

        return Db::table($tableName);
    }

    /**
     * 管理员
     * @return BelongsTo
     */
    public function admin(): BelongsTo
    {
        return $this->belongsTo('app\admin\model\Admin', 'audit_user_id', 'id');
    }
}